import { Button, Space, Table, Upload, UploadFile, UploadProps } from "antd";
import type { ColumnsType } from "antd/es/table";
import { RcFile } from "antd/es/upload";
import React, { useEffect, useRef, useState } from "react";
import { ResPage, ResultData } from "../../../api/interface";
import {
    deleteUser,
    exportExcal,
    findPage,
    importExcal,
} from "../../../api/modules/user";
import ModalCom from "./Model";
import TableSearch from "./TableSearch";

import { RefType } from './interface';
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
  id: number;
}

const List: React.FC = () => {
    const [ data, setData ] = useState<any>([]);
    const modalRef = useRef<RefType>(null);
    const [ fileList, setFileList ] = useState<UploadFile[]>([]);
    const [ paginationParams, setPaginationParams ] = useState<any>({
        pageSize: 10,
        pageNum: 1,
        total: 20,
    });
    const [ searchParmas, setSearchParams ] = useState({
        username: "",
        address: "",
        email: "",
    });
    const addModal = (flag?: DataType) => {
        if (!flag) {
      modalRef.current!.showModal();
        } else {
      modalRef.current!.showModal(flag);
        }
    };
    const handleDelete = async ({ id }: { id: number }) => {
        const result = await deleteUser(id);
        if (result) {
            getList();
        }
    };
    const columns: ColumnsType<DataType> = [
        {
            title: "用户名",
            dataIndex: "username",
            key: "username",
            render: (text) => <a>{text}</a>,
        },
        {
            title: "昵称",
            dataIndex: "nickname",
            key: "nickname",
        },
        {
            title: "角色",
            dataIndex: "role",
            key: "role",
        },
        {
            title: "地址",
            dataIndex: "address",
            key: "address",
        },
        {
            title: "手机号码",
            dataIndex: "phone",
            key: "phone",
        },
        {
            title: "Action",
            key: "id",
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => addModal(record)}>编辑 {record.name}</a>
                    <a onClick={() => handleDelete(record)}>删除</a>
                </Space>
            ),
        },
    ];
    const getList = async () => {
        const result = (await findPage({
            ...paginationParams,
            ...searchParmas,
        })) as ResultData<ResPage<any>>;
        if (result.data?.records) {
            setData(result.data.records);
            paginationParams.total = result.data.total;
        }
    };
    const handleImport = async (options:any) => {
        const { file } = options;
        const formData = new FormData();
        formData.append("file", file as RcFile);
        await importExcal(formData);
        getList();
    };
    useEffect(() => {
        getList();
    }, [ paginationParams, searchParmas ]);
    const onChange = async (page: number, pageSize: number) => {
        setPaginationParams({ ...paginationParams, pageNum: page, pageSize });
    };

    const onSearch = (searchParams: any) => {
    // setPaginationParams({...paginationParams,...searchParams})
        setSearchParams(searchParams);
    };
    const handleExport = async () => {
        const result = (await exportExcal()) as unknown as Blob;
        const blob = new Blob([ result ], { type:'.xlsx' });
        const blobUrl = window.URL.createObjectURL(blob);
        download(blobUrl);
    };
    const download = (blobUrl: string)=> {
        const a = document.createElement('a');
        a.style.display = 'none';
        a.download = '用户表' + '.xlsx';
        a.href = blobUrl;
        a.click();
        window.URL.revokeObjectURL(blobUrl);
    };
    const props: UploadProps = {
        onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
        },
        fileList,
    };
    return (
        <>
            <Space>
                <Button type="primary" onClick={() => addModal()}>
          新增
                </Button>
                <Button type="primary" onClick={handleExport}>
          导出
                </Button>
                <Upload {...props} showUploadList={false} customRequest={handleImport}>
                    <Button type="primary">上传</Button>
                </Upload>
                <TableSearch onSearch={onSearch} />
            </Space>
            <Table
                rowKey="id"
                columns={columns}
                dataSource={data}
                pagination={{
                    total: paginationParams.total,
                    pageSize: paginationParams.pageSize,
                    current: paginationParams.pageNum,
                    onChange: onChange,
                    showSizeChanger: true,
                    showTotal: (total) => total,
                }}
            />
            <ModalCom ref={modalRef} getList={getList} />
        </>
    );
};

export default List;
